package com.webserver.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 该线程负责与指定客户端完成HTTP协议的交互过程
 *
 */
public class ClientHandler implements Runnable{
    private Socket socket;

    public ClientHandler(Socket socket){
        this.socket = socket;
    }

    public void run() {
        //测试:读取客户端发送过来的内容
        try {
            //1.解析请求

            //2.处理请求

            //3.发送响应

            //1.1解析请求行
            String line = readLine();
            System.out.println("请求行内容:"+line);
            String[] arr = line.split("\\s");
            String method = arr[0];
            String uri = arr[1];
            String proyocl = arr[2];

            System.out.println("method:"+method);
            System.out.println("uri:"+uri);
            System.out.println("proyocl:"+proyocl);
            //1.2解析消息头
            //key保存消息头的名字,value保存消息头对应的值
            Map<String,String> headers = new HashMap<>();
            while (true) {
                line = readLine();
//                if (line.length==0){//当单独读取到CRLF时停止
//               if ("".equals(line)){//当单独读取到CRLF时停止
                if (line.isEmpty()){//当单独读取到CRLF时停止
                    break;
                }
                System.out.println("消息头:"+line);

                String[] arr1 = line.split(":\\s");
                headers.put(arr1[0],arr1[1]);
            }
            System.out.println("消息头1:"+headers);
//            Set<String> keySet = headers.keySet();
//            keySet.forEach(e -> System.out.println(e));


        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public String readLine() throws IOException {

            InputStream in = socket.getInputStream();
            int d;
            char pre = 'a';//记录上次读取到的字符
            char cur = 'a';//记录本次读取到的字符
            StringBuilder builder = new StringBuilder();

            while ((d = in.read())!=-1){
                cur  = (char) d;//本次读取到的字符
                if (pre==13&&cur==10){//是否连续读取到了回车+换行
                    break;
                }
                builder.append(cur);
                pre = cur;
            }
           return builder.toString().trim();

    }

}
